<?php
// +----------------------------------------------------------------------
// | ZengCMS [ 火火 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://zengcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 火火 <zengcms@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | JwtToken服务类
// +----------------------------------------------------------------------
namespace app\api\service;

use think\facade\Cache;
use app\api\lib\JwtAuth;
use app\api\lib\exception\MissException;

class JwtToken
{
    /**
     * 生成token令牌
     * @param [type] $data 用户数组数据
     * @return void
     */
    public static function generateToken($data)
    {
        return JwtAuth::getInstance()->setDataFromArr($data)->encode()->getToken();
    }
    /**
     * 检查用户专有权限
     * @param [type] $token
     * @return void
     */
    public static function needPermission($token)
    {
        // 从缓存中获取当前用户指定身份标识scope
        $uid = self::getCurrentTokenVar($token,'uid');
        if ($uid) {
            return true;
        } else {
            throw new MissException([
                'message' => '权限不够！',
                'httpCode' => 403
            ]);
        }
    }
    /**
     * 从缓存中获取当前用户指定身份标识
     * @param [type] $token
     * @param [type] $key 字段，例：'uid'或['uid']
     * @return void
     */
    public static function getCurrentTokenVar($token, $keys)
    {
        $result = self::verifyToken($token);
        if ($result['isValid'] == false && empty($result['refresh_token'])) 
        {
            throw new MissException([
                'message' => '您尚未登录！',
                'httpCode' => 403
            ]);
        }
        $jwt = JwtAuth::getInstance()->setToken($token)->decode();
        if(is_array($keys)){
            return $jwt->getDataArrByKey($keys);
        }
        return $jwt->getDataStringByKey($keys);
    }
    /**
     * 检查token是否存在，即是否有效
     * @param  [type] $token [description]
     * @return [type]        [description]
     */
    public static function verifyToken($token)
    {
        if (!$token) {
            throw new MissException([
                'message' => 'token不允许为空！',
            ]);
        }
        $jwt = JwtAuth::getInstance()->setToken($token)->decode();
        // 获取生成token时间
        $time = $jwt->getDataStringByKey('time');
        // 获取ip
        $ip = $jwt->getDataStringByKey('ip');
        // 检查token前两部分即头部header和负荷playload
        if ($jwt->validate()) {
            if ($ip != get_reluser_ip()) {
                throw new MissException([
                    'message' => '登录异常！'
                ]);
            }
            $refresh_token = '';
            // 检查token最后一部分即signature签名
            if ($jwt->verify()) {
                $valid = true;
                if (time() - $time <= 30 * 24 * 60 * 60) {
                    // $refresh_token = $jwt->getData();
                    $refresh_token = $token;
                }
            } else {
                $valid = false;
            }
        } else {
            $valid = false;
            $refresh_token = '';
            if (time() - $time <= 30 * 24 * 60 * 60) {
                // $refresh_token = $jwt->getData();
                $refresh_token = $token;
            }
        }
        return [
            'isValid' => $valid,//判断是否登录
            'refresh_token' => $refresh_token,//通过refresh_token获取新的token
        ];
    }
}
